/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Parser;

import compiler.CMinusCompiler;
import java.util.HashMap;
import lowlevel.Function;
import lowlevel.Operand;
import lowlevel.Operation;

/**
 *
 * @author maxmuhlenkamp
 */
public class Identifier extends Expression {
    String idName;
    Expression location;
    
    public Identifier(String idName, Expression location){
        this.location = location;
        this.idName = idName;
    }

    @Override
    void print(String indent) {
        CMinusParser.oFile.println(indent + "Identifier:");
        if(location != null){
            CMinusParser.oFile.println(indent + "  " + idName);
            CMinusParser.oFile.println(indent + "  ArrayLocation:");
            location.print(indent + "    ");
        }
        else{
            CMinusParser.oFile.println(indent + "  " + idName);
        }
        CMinusParser.oFile.flush();
    }

    @Override
    public void genLLCode(Function func) {
        HashMap table = func.getTable();
        if(table.containsKey(idName)){
            regNum = (int)table.get(idName);
        }
        else if(CMinusCompiler.globalHash.containsKey(idName)){
            regNum = func.getNewRegNum();
            Operation load = new Operation(Operation.OperationType.LOAD_I, func.getCurrBlock());
            Operand dest = new Operand(Operand.OperandType.REGISTER, regNum);
            Operand source = new Operand(Operand.OperandType.STRING, idName);
            Operand offset;
            if(location == null){
                offset = new Operand(Operand.OperandType.INTEGER, 0);
            }
            else{
                offset = new Operand(Operand.OperandType.REGISTER, location.getRegNum());
            }
            
            load.setDestOperand(0, dest);
            load.setSrcOperand(0, source);
            load.setSrcOperand(1, offset);
            
            func.getCurrBlock().appendOper(load);
        }
        else{
            System.err.println("Identifier not previously declared");
        }
    }
}
